package api;

import Util.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import compile.Answer;
import compile.Question;
import compile.Task;
import problom.Problem;
import problom.ProblemDAO;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CompileServlet extends HttpServlet {
    private Gson gson=new GsonBuilder().create();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String body= HttpUtil.readBody(req);
        CompileRequest compileRequest=gson.fromJson(body,CompileRequest.class);
        ProblemDAO problemDao=new ProblemDAO();
        Problem problem=problemDao.selectOne(compileRequest.getId());
        String testCode=problem.getTestCode();
        String requestCode=compileRequest.getCode();
        String finalCOde=merge(requestCode,testCode);
        Task task=new Task();
        Question question=new Question();
        Answer a=null;
        try {
            a=task.compileAndRun(question);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        CompileResponse compileResponse=new CompileResponse();
        compileResponse.setError(a.getError());
        compileResponse.setReason(a.getReason());
        compileResponse.setStdout(a.getStdout());
        String respString=gson.toJson(compileResponse);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(respString);
    }
    private String merge(String requestCode,String testCode){
        //先找到requestCode末尾的 } ，并截取出前面的代码
        int pos=requestCode.lastIndexOf("}");
        if(pos==-1){
            return null;
        }
        //2.把testCode拼接到后面再拼接上 } 即可
        return requestCode.substring(0,pos)+testCode+"}";
    }

}
